package demo.socket;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpPicServer {

	public static void main(String[] args) throws IOException {
		@SuppressWarnings("resource")
		ServerSocket ss = new ServerSocket(10000);
		System.out.println("��������");
		while (true) {
			Socket s = ss.accept();
			String name = s.getInetAddress().getHostName();
			new Thread(new PicThread(s, name)).start();
		}
	}

}

class PicThread implements Runnable {

	private Socket s;
	private String name;

	public PicThread(Socket s, String name) {
		this.s = s;
		this.name = name;
	}

	public void run() {
		try {
			BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
			int num = 1;
			File f = new File(name + ".jpg");
			while (f.exists())
				f = new File(name + "(" + num++ + ").jpg");
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
			byte[] buf = new byte[1024];
			int len = 0;
			while ((len = bis.read(buf)) != -1) {
				bos.write(buf, 0, len);
				bos.flush();
			}
			bos.close();
			s.getOutputStream().write("�ϴ��ɹ�".getBytes());
			System.out.println(name + " upload \"" + f.getName() + " \" succeed.");
			s.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
